<?php
/*
 * Author: Quan Van Sinh
 * Email : sinhvnb@vietnambiz.com
 * Mobile: 0972405165
 */
//category function
function addNewCategory() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmNewsAddCategory'])) {
        $data = array();
        if($_POST['cat_title']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
        }
        $data['cat_title'] = $_POST['cat_title'];
        $data['cat_parent'] = $_POST['cat_parent'];
        $data['cat_link'] = create_link($_POST['cat_title']);
        $data['cat_link'] = checkCatLinkExist($data['cat_link']);
        $data['cat_description'] = $_POST['cat_description'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['cat_active'] = $_POST['cat_active'];
        $data['user_id'] = $_SESSION['adlogin']["id"];
        $data['lang'] = $_SESSION['adlang'];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $bigestOrder = getBigestOrder();
            $data['cat_order'] = $bigestOrder+1;
            $db->exec_insert('cat_news', $data);
            $CONFIG["success_message"] = "<li>Thêm mới danh mục thành công!</li>";
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
        }
    }
}

function editUpdateCategory() {
    global $db,$CONFIG;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        if(isset($_POST['submitFrmNewsAddCategory'])) {//update category
            $data = array();
            if($_POST['cat_title']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
            }
            $data['cat_title'] = $_POST['cat_title'];
            $data['cat_parent'] = $_POST['cat_parent'];
            //$data['cat_link'] = create_link($_POST['cat_title']);
            $data['cat_description'] = filter($_POST['cat_description']);
            $data['create_date'] = date('Y-m-d H:i:s');
            $data['cat_active'] = filter($_POST['cat_active']);
            $data['user_id'] = $_SESSION['adlogin']["id"];
            if($CONFIG["error_message"]=='') {
                $db->exec_update('cat_news', $data, " cat_id=$cat_id ");
                $CONFIG["success_message"] = "<li>Cập nhật danh mục thành công!</li>";
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action')));
                }
            }
        }
        return $db->query_first("SELECT * FROM cat_news WHERE cat_id=$cat_id");
    }
}

function deleteNewsCat() {
    global $db;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        $arrChildCatNews = getCatNewsIdToArray($cat_id,$trees=null);
        for($i=0;$i<count($arrChildCatNews);$i++) {
            if(intval($arrChildCatNews[$i])>0) {
                $db->exec_delete('cat_news',"cat_id=".$arrChildCatNews[$i]);
            }
        }
        $db->exec_delete('cat_news',"cat_id=$cat_id");
    }
}

function getCatNewsIdToArray($parent_id = 0,$trees=null) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT cat_id FROM cat_news WHERE  cat_parent = ".intval($parent_id));
    if($rsCat) {
        while($rs = $db->fetch_array($rsCat)) {
            $trees[] = $rs['cat_id'];
            $trees = getCatNewsIdToArray($rs['cat_id'],$trees);
        }
    }
    return $trees;
}

function listAllNewsCategory($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM cat_news WHERE  cat_parent = ".intval($parent_id)." AND lang='".$_SESSION["adlang"]."' ORDER BY cat_order");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['cat_parent']==0) {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$space.$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }
        $trees = listAllNewsCategory($rs['cat_id'],$space.'----',$trees);
    }
    return $trees;
}

function multiActionCategoryNews() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrCatId = $_REQUEST['arr_cat_id'];
        switch($_REQUEST['formNewsCategoryViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_delete('cat_news','cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case "setStatusYes": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_news',array("cat_active"=>'yes'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case "setStatusNo": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_news',array("cat_active"=>'no'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}

//order category
function orderNewsCategory() {
    global $db,$CONFIG,$option;
    if(isset($_POST['submitFrmNewsOrder']) && $_POST['submitFrmNewsOrder']=="Submit") {//update
        $arrNewsCatID = $_POST['news_order'];
        if(count($arrNewsCatID)) {
            for($i=0;$i<count($arrNewsCatID);$i++) {
                if(intval($arrNewsCatID[$i])>0) {
                    $db->exec_update('cat_news',array("cat_order"=>$i),'cat_id='.intval($arrNewsCatID[$i]));
                }
            }
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL.get_string_url(array('action')));
            }else {
                return listAllNewsCategory();
            }
        }else {
            return listAllNewsCategory();
        }
    }else {//show
        return listAllNewsCategory();
    }

}

// Le Trong Phuc
//end category function
//news
//Uporder category function
function upOrderNewsCategory() {
    global $db;
    $cat_id = $_REQUEST['cat_id'];

    $arr_cat_order = getOrder($cat_id);
    $cat_order = $arr_cat_order['cat_order'];
    $cat_parent = $arr_cat_order['cat_parent'];

    $arrCatUp = getUpOrder($cat_order,$cat_parent);
    $catUpId = $arrCatUp['cat_id'];
    $catUpOrder = $arrCatUp['cat_order'];
    $data = array();
    $data['cat_order'] = $cat_order;
    $dataUp = array();
    $dataUp['cat_order'] = $catUpOrder;
    //$db->exec_update('cat_news', $dataUp, " cat_id=$catUpId");
    if(intval($catUpId>0)) {
        $db->query("update cat_news set cat_order=$catUpOrder where cat_id=$cat_id");
        $db->query("update cat_news set cat_order=$cat_order where cat_id=$catUpId");
    }
}
function getOrder($cat_id) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_order,cat_parent FROM cat_news WHERE  cat_id = ".intval($cat_id));
    return $rsCat;
}
function getUpOrder($cat_order,$cat_parent) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_news WHERE  cat_order<$cat_order AND cat_parent=$cat_parent ORDER BY cat_order DESC");
    return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
}
function downOrderNewsCategory() {
    global $db;
    $cat_id = $_REQUEST['cat_id'];

    $arr_cat_order = getOrder($cat_id);
    $cat_order = $arr_cat_order['cat_order'];
    $cat_parent = $arr_cat_order['cat_parent'];
    $arrCatDown = getDownOrder($cat_order,$cat_parent);
    $catDownId = $arrCatDown['cat_id'];
    $catDownOrder = $arrCatDown['cat_order'];
    $data = array();
    $data['cat_order'] = $cat_order;


    $dataUp = array();
    $dataUp['cat_order'] = $catDownOrder;
    //$db->exec_update('cat_news', $dataUp, " cat_id=$catUpId");
    if(intval($catDownId)>0) {
        $db->query("update cat_news set cat_order=$catDownOrder where cat_id=$cat_id");
        $db->query("update cat_news set cat_order=$cat_order where cat_id=$catDownId");
    }


}
function getDownOrder($cat_order,$cat_parent) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_news WHERE  cat_order>$cat_order AND cat_parent=$cat_parent ORDER BY cat_order ASC");
    return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
}

function getBigestOrder() {
    global $db;
    $rsCat = $db->query_first("SELECT cat_order FROM cat_news ORDER BY cat_order DESC");
    return $rsCat['cat_order'];
}
// End Le Trong Phuc
//end category function
//news
function addNewNews() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmNewsAdd'])) {
        $data = array();
        if($_POST['title']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
        }
        if($_POST['description']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập miêu tả!</li>";
        }
        if($_POST['content']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập nội dung!</li>";
        }
        $data['title'] = $_POST['title'];
        $data['title_link'] = create_link($_POST['title']);
        $data['title_link'] = checkNewsLinkExist($data['title_link']);
        $data['cat_id'] = $_POST['cat_id'];
        $data['image'] = $_POST['image'];
        $data['description'] = $_POST['description'];
        $data['content'] = $_POST['content'];
        $data['type'] = $_POST['type'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['user_id'] = $_SESSION['adlogin']["id"];
        $data['lang'] = $_SESSION['adlang'];
        $tags = $_POST['keyword'];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $db->exec_insert('news', $data);
            $newsId = mysql_insert_id();

            //insert data to tags
            for($i=0;$i<count($tags);$i++) {
                if($tags[$i]!='') {
                    $tempTags = checkTagExist($tags[$i]);
                    if($tempTags=='donthave') {//chua ton` tai tag nay nen insert vao database
                        $tags_link = create_link($tags[$i]);
                        $word_count = str_word_count(nosign($tags[$i]));
                        $db->query("INSERT INTO tags_news (tags, tags_link, word_count) VALUES ('$tags[$i]', '$tags_link','$word_count')");
                        $db->query("INSERT INTO news_relate_tags (news_id,tag_id) VALUES ($newsId,".mysql_insert_id().")");
                    }else {//ton tai rui nen lay id (chinh la $tempTags)
                        $db->query("INSERT INTO news_relate_tags (news_id,tag_id) VALUES ($newsId,$tempTags)");
                    }
                }
            }
            if($_POST['submitType']=='exit') {
            //server_redirect(ADMIN_URL . '?module=news');
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
            $CONFIG["success_message"] = "<li>Thêm mới tin thành công!</li>";
        }

    }
}

function checkNewsLinkExist($newsLink) {
    global $db;
    $rs = $db->query_first("SELECT id,title_link FROM news WHERE title_link='$newsLink'");
    if(intval($rs['id'])>0) {
        $newsLink = $rs['title_link'].'-'.rand(0,9);
        checkNewsLinkExist($newsLink);
    }
    return $newsLink;
}

function checkCatLinkExist($newsCatLink) {
    global $db;
    $rs = $db->query_first("SELECT cat_id,cat_link FROM cat_news WHERE cat_link='$newsCatLink'");
    if(intval($rs['cat_id'])>0) {
        $newsCatLink = $rs['cat_link'].'-'.rand(0,9);
        checkCatLinkExist($newsCatLink);
    }
    return $newsCatLink;
}

function checkTagExist($tag) {
    global $db;
    $rs = $db->query_first("SELECT id FROM tags_news WHERE tags='$tag'");
    if($rs) {
        return $rs['id'];
    }else {
        return 'donthave';
    }
}

function editUpdateNews() {
    global $db,$CONFIG;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        if(isset($_POST['submitFrmNewsAdd'])) {//update category
            $data = array();
            if($_POST['title']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
            }
            if($_POST['description']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập miêu tả!</li>";
            }
            if($_POST['content']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập nội dung!</li>";
            }
            $data['title'] = $_POST['title'];
            //$data['title_link'] = create_link($_POST['title']);
            $data['cat_id'] = $_POST['cat_id'];
            $data['image'] = $_POST['image'];
            $data['description'] = $_POST['description'];
            $data['content'] = $_POST['content'];
            $data['type'] = $_POST['type'];
            //$data['create_date'] = date('Y-m-d H:i:s');
            $data['user_id'] = $_SESSION['adlogin']["id"];

            if($CONFIG["error_message"]=='') {
                $db->exec_update('news', $data, " id=$id ");
                $CONFIG["success_message"] = "<li>Cập nhật tin thành công!</li>";

                $removedTags = explode(',', $_POST['removedTags']);
                //delete tag had been removed
                for($i=0;$i<count($removedTags);$i++) {
                    if($removedTags[$i]!='') {
                        $rsRemoveTagId = $db->query_first("SELECT id FROM tags_news WHERE tags='".$removedTags[$i]."'");
                        if($rsRemoveTagId['id']!=0) {
                            $db->query("DELETE FROM news_relate_tags WHERE tag_id = ".$rsRemoveTagId['id']);
                        }
                    }
                }
                $tags = $_POST['keyword'];
                //insert data to tags
                for($i=0;$i<count($tags);$i++) {
                    if($tags[$i]!='') {
                        $tempTags = checkTagExist($tags[$i]);
                        if($tempTags=='donthave') {//chua ton` tai tag nay nen insert vao database
                            $tags_link = create_link($tags[$i]);
                            $word_count = str_word_count(nosign($tags[$i]));
                            $db->query("INSERT INTO tags_news (tags, tags_link, word_count) VALUES ('$tags[$i]', '$tags_link', '$word_count')");
                            $db->query("INSERT INTO news_relate_tags (news_id,tag_id) VALUES ($id,".mysql_insert_id().")");
                        }else {//ton tai rui nen lay id (chinh la $tempTags)
                            $db->query("INSERT INTO news_relate_tags (news_id,tag_id) VALUES ($id,$tempTags)");
                        }
                    }
                }

                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action','id')));
                }
            }
        }
        $rsNewsEdit = $db->query_first("SELECT * FROM news WHERE id=$id");
        $rsNewsTagEdit = $db->query("SELECT tn.* FROM tags_news tn LEFT JOIN news_relate_tags nrt ON tn.id=nrt.tag_id WHERE nrt.news_id=".intval($id));
        return array("rsNewsEdit"=>$rsNewsEdit,"rsNewsTagEdit"=>$rsNewsTagEdit);
    }else {
        server_redirect(SITE_URL . get_string_url(array('action','id')));
    }

}

function newsDetail() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        return $db->query_first("SELECT * FROM news WHERE id=$id");
    }else {
        server_redirect(ADMIN_URL.'?module=news');
    }
}

function deleteNews() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        $db->exec_delete('news',"id=$id");
    }
}

function listAllNews() {
    global $db,$CONFIG;
    if(intval($_REQUEST['page'])>0) {
        $page = $_REQUEST['page'];
    }else {
        $page = 1;
    }

        if($_REQUEST['keyword']!='') {
            $searchCondition = ' AND (n.title LIKE \'%'.$_REQUEST['keyword'].'%\' OR n.description LIKE \'%'.$_REQUEST['keyword'].'%\' OR n.content LIKE \'%'.$_REQUEST['keyword'].'%\')';
        }
        if(intval($_REQUEST['cat_id'])>0) {
            $arrCatId = getCatNewsIdToArray($_REQUEST['cat_id']);
            array_push($arrCatId,$_REQUEST['cat_id']);
            if(count($arrCatId)>0) {
                $strCatId = implode(',', $arrCatId);
                $searchCondition .= " AND c.cat_id IN ($strCatId)";
            }else {
                $searchCondition .= " AND c.cat_id =".$_REQUEST['cat_id'];
            }
        }
        //echo $searchCondition;
        $rsNews = $db->query("SELECT n.id FROM news n LEFT JOIN cat_news c ON n.cat_id = c.cat_id WHERE 1 $searchCondition  AND n.lang='".$_SESSION['adlang']."' ORDER BY n.create_date DESC");
        $totalRows =  $db->num_rows($rsNews);
        $totalPages = ceil($totalRows/$CONFIG ['rows_per_page_news']);
        $start = (($page*$CONFIG ['rows_per_page_news'])-$CONFIG ['rows_per_page_news']);
        $limit = $CONFIG ['rows_per_page_news'];

        $rs = $db->query("SELECT n.id,n.cat_id,n.title,n.title_link,n.description,n.content,n.create_date,n.type,n.active,c.cat_title
                            FROM news n LEFT JOIN cat_news c ON n.cat_id = c.cat_id
                            WHERE 1 $searchCondition  AND n.lang='".$_SESSION['adlang']."' ORDER BY n.create_date DESC LIMIT $start,$limit");
        //chuyen ve` truong truoc neu' trang hien tai khong co' ban ghi nao (truong hop xoa)
        if($db->num_rows($rs)<1) {
            $page = $page - 1;
            if($page>1) {
                server_redirect(get_string_url()."&page=".$page);
            }

        }
        return array(
        "rs"=>$rs,
        "page"=>$page,
        "totalPages"=>$totalPages
        );
}

function multiActionNews() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrNewsId = $_REQUEST['arr_news_id'];
        switch($_REQUEST['formNewsViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_delete('news','id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case "setStatusYes": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'yes'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case "setStatusPending": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'pending'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case "setStatusNo": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'no'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}
?>
